package bbk.nfc;

import java.util.ArrayList;


import bbk.nfc.opt.OptApp;
import bbk.nfc.opt.Vars;
import bbk.nfc.persistent.NfcPref;
import bbk.nfc.root.rootTool;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity
{
	public static final String TAG = "NFC_MAIN";
	private GridView mGrid;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		Log.i(TAG, "onCreate:" + savedInstanceState);
		setContentView(R.layout.activity_main);
		mGrid = (GridView) findViewById(R.id.main_grid);
		mGrid.setAdapter(new GridAdapter(this));
		mGrid.setOnCreateContextMenuListener(this);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// TODO Auto-generated method stub
		Intent intent;
		switch (item.getItemId())
		{
		case R.id.menu_write:
			intent = new Intent(this, NfcWriteActivity.class);
			intent.putExtra(NfcWriteActivity.TYPE, NfcWriteActivity.TYPE_WRITE);
			intent.putExtra(NfcWriteActivity.WRITE_DATA, getWriteStringAsNdef());
			startActivity(intent);
			break;
		case R.id.menu_format:
			intent = new Intent(this, NfcWriteActivity.class);
			intent.putExtra(NfcWriteActivity.TYPE, NfcWriteActivity.TYPE_FORMAT);
			startActivity(intent);
			break;
		case R.id.menu_root:
			rootTool.root(this);
			break;
		case R.id.menu_test:
			NfcPref mPref = NfcPref.get(this);
			String a0 = mPref.codeAction(new String[]
			{ new String(new byte[]
			{ Vars.WIFI , Vars.TOGGLE }) });
			String a1 = mPref.codeAction(new String[]
			{ new String(new byte[]
			{ Vars.PHONE }) , "1379882473sdwdwd5" });
			String t = mPref.codeTask(new String[]
			{ a0 , a1 });
			mPref.savePref(t, 0);
			mPref.processTask(0);
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onActivityResult(int reqCode, int resultCode, Intent data)
	{
		super.onActivityResult(reqCode, resultCode, data);
		
		switch (reqCode)
		{
		case (OptApp.PICK_CONTACT):
			if (resultCode == Activity.RESULT_OK)
			{
				Uri contactData = data.getData();
				Cursor c = managedQuery(contactData, null, null, null, null);
				if (c.moveToFirst())
				{
					int phoneCount = c.getInt(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
					String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
					final CharSequence[] phoneNumber = new CharSequence[phoneCount];
					if (phoneCount > 0)
					{
						int i = 0;
						Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
						while (phones.moveToNext())
						{
							phoneNumber[i++] = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						}
						phones.close();
						AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle(R.string.hello_world).setItems(phoneNumber, new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog, int which)
							{
								//							new AlertDialog.Builder(MainActivity.this).setMessage("You selected: " + which + " , " + phoneNumber[which]).show();
							}
						});
						AlertDialog alertDialog = builder.create();
						alertDialog.show();
					}
				}
				c.close();
			}
			break;
		case (OptApp.PICK_APP):
			if (resultCode == Activity.RESULT_OK)
			{
				Bundle extras = data.getExtras();
				String s = extras.getString("pkg_name");
				Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
			}
			break;
		}
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		Log.i(TAG, "onResume:" + getIntent().getAction());
	}
	
	public void onPause()
	{
		super.onPause();
		Log.i(TAG, "onPause");
	}
	
	private NdefMessage getWriteStringAsNdef()
	{
		String s = getPackageName();
		byte[] payload =
		{ 0x32 , 0x00 , 0x54 , 0x00 };
		//		NdefRecord r0 = NdefRecord.createExternal("bbk.nfc", "ext", payload);
		NdefRecord r0 = NdefRecord.createUri("http://vivo.com.cn");
		return new NdefMessage(new NdefRecord[]
		{ r0 });
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("人物简介");
		menu.add(0, 1, 0, "Edit");
		menu.add(0, 2, 0, "Rename");
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId())
		{
		case 1:
			//			editNote(info.position);
			break;
		case 2:
			//			r(info.position);
			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIconAttribute(android.R.attr.alertDialogIcon);
			builder.setTitle(R.string.hello_world);
			builder.setView(textEntryView);
			builder.setPositiveButton(R.string.root, new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int whichButton)
				{
					
					/* User clicked OK so do some stuff */
				}
			});
			builder.setNegativeButton(R.string.app_name, new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int whichButton)
				{
					
					/* User clicked cancel so do some stuff */
				}
			});
			AlertDialog dia =  builder.create();
			dia.show();
			break;
		default:
		}
		return super.onContextItemSelected(item);
	}
	
	private ArrayList < String > mNfcTasks = new ArrayList < String >(4);
	
	class GridAdapter extends BaseAdapter
	{
		protected final LayoutInflater mInflater;
		
		public GridAdapter(Context context)
		{
			mInflater = LayoutInflater.from(context);
			mNfcTasks.add("home");
			mNfcTasks.add("car");
			mNfcTasks.add("office");
			mNfcTasks.add("sos");
			
		}
		
		public int getCount()
		{
			return mNfcTasks.size();
		}
		
		public Object getItem(int position)
		{
			return mNfcTasks.get(position);
		}
		
		public long getItemId(int position)
		{
			return position;
		}
		
		public View getView(int position, View convertView, ViewGroup parent)
		{
			String info = mNfcTasks.get(position);
			if (convertView == null)
			{
				convertView = (View) mInflater.inflate(R.layout.main_grid_item, mGrid, false);
			}
			else
			{
			}
			TextView txt = (TextView) convertView.findViewById(R.id.grid_text);
			txt.setText(info);
			return convertView;
		}
		
	}
}
